/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package entidade.controller.JPA;

import entidade.controller.JPA.exceptions.NonexistentEntityException;
import entidade.controller.JPA.exceptions.RollbackFailureException;
import entidade.persistencia.EntradaSaida;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import entidade.persistencia.Venda;
import java.util.ArrayList;
import java.util.List;
import entidade.persistencia.FolhaPagamento;
import entidade.persistencia.Manutencao;
import entidade.persistencia.Compra;
import java.util.Date;
import javax.transaction.UserTransaction;

/**
 *
 * @author victorinox
 */
public class EntradaSaidaJpaController {

    @Resource
    private UserTransaction utx = null;
    @PersistenceUnit(unitName = "globalimage2PU")
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(EntradaSaida entradaSaida) throws RollbackFailureException, Exception {
        if (entradaSaida.getVendaCollection() == null) {
            entradaSaida.setVendaCollection(new ArrayList<Venda>());
        }
        if (entradaSaida.getFolhaPagamentoCollection() == null) {
            entradaSaida.setFolhaPagamentoCollection(new ArrayList<FolhaPagamento>());
        }
        if (entradaSaida.getManutencaoCollection() == null) {
            entradaSaida.setManutencaoCollection(new ArrayList<Manutencao>());
        }
        if (entradaSaida.getCompraCollection() == null) {
            entradaSaida.setCompraCollection(new ArrayList<Compra>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            List<Venda> attachedVendaCollection = new ArrayList<Venda>();
            for (Venda vendaCollectionVendaToAttach : entradaSaida.getVendaCollection()) {
                vendaCollectionVendaToAttach = em.getReference(vendaCollectionVendaToAttach.getClass(), vendaCollectionVendaToAttach.getVendaId());
                attachedVendaCollection.add(vendaCollectionVendaToAttach);
            }
            entradaSaida.setVendaCollection(attachedVendaCollection);
            List<FolhaPagamento> attachedFolhaPagamentoCollection = new ArrayList<FolhaPagamento>();
            for (FolhaPagamento folhaPagamentoCollectionFolhaPagamentoToAttach : entradaSaida.getFolhaPagamentoCollection()) {
                folhaPagamentoCollectionFolhaPagamentoToAttach = em.getReference(folhaPagamentoCollectionFolhaPagamentoToAttach.getClass(), folhaPagamentoCollectionFolhaPagamentoToAttach.getFolhaPagamentoId());
                attachedFolhaPagamentoCollection.add(folhaPagamentoCollectionFolhaPagamentoToAttach);
            }
            entradaSaida.setFolhaPagamentoCollection(attachedFolhaPagamentoCollection);
            List<Manutencao> attachedManutencaoCollection = new ArrayList<Manutencao>();
            for (Manutencao manutencaoCollectionManutencaoToAttach : entradaSaida.getManutencaoCollection()) {
                manutencaoCollectionManutencaoToAttach = em.getReference(manutencaoCollectionManutencaoToAttach.getClass(), manutencaoCollectionManutencaoToAttach.getManutencaoId());
                attachedManutencaoCollection.add(manutencaoCollectionManutencaoToAttach);
            }
            entradaSaida.setManutencaoCollection(attachedManutencaoCollection);
            List<Compra> attachedCompraCollection = new ArrayList<Compra>();
            for (Compra compraCollectionCompraToAttach : entradaSaida.getCompraCollection()) {
                compraCollectionCompraToAttach = em.getReference(compraCollectionCompraToAttach.getClass(), compraCollectionCompraToAttach.getCompraId());
                attachedCompraCollection.add(compraCollectionCompraToAttach);
            }
            entradaSaida.setCompraCollection(attachedCompraCollection);
            em.persist(entradaSaida);
            for (Venda vendaCollectionVenda : entradaSaida.getVendaCollection()) {
                vendaCollectionVenda.getEntradaSaidaCollection().add(entradaSaida);
                vendaCollectionVenda = em.merge(vendaCollectionVenda);
            }
            for (FolhaPagamento folhaPagamentoCollectionFolhaPagamento : entradaSaida.getFolhaPagamentoCollection()) {
                folhaPagamentoCollectionFolhaPagamento.getEntradaSaidaCollection().add(entradaSaida);
                folhaPagamentoCollectionFolhaPagamento = em.merge(folhaPagamentoCollectionFolhaPagamento);
            }
            for (Manutencao manutencaoCollectionManutencao : entradaSaida.getManutencaoCollection()) {
                manutencaoCollectionManutencao.getEntradaSaidaCollection().add(entradaSaida);
                manutencaoCollectionManutencao = em.merge(manutencaoCollectionManutencao);
            }
            for (Compra compraCollectionCompra : entradaSaida.getCompraCollection()) {
                compraCollectionCompra.getEntradaSaidaCollection().add(entradaSaida);
                compraCollectionCompra = em.merge(compraCollectionCompra);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(EntradaSaida entradaSaida) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            EntradaSaida persistentEntradaSaida = em.find(EntradaSaida.class, entradaSaida.getEntradaSaidaId());
            List<Venda> vendaCollectionOld = persistentEntradaSaida.getVendaCollection();
            List<Venda> vendaCollectionNew = entradaSaida.getVendaCollection();
            List<FolhaPagamento> folhaPagamentoCollectionOld = persistentEntradaSaida.getFolhaPagamentoCollection();
            List<FolhaPagamento> folhaPagamentoCollectionNew = entradaSaida.getFolhaPagamentoCollection();
            List<Manutencao> manutencaoCollectionOld = persistentEntradaSaida.getManutencaoCollection();
            List<Manutencao> manutencaoCollectionNew = entradaSaida.getManutencaoCollection();
            List<Compra> compraCollectionOld = persistentEntradaSaida.getCompraCollection();
            List<Compra> compraCollectionNew = entradaSaida.getCompraCollection();
            List<Venda> attachedVendaCollectionNew = new ArrayList<Venda>();
            for (Venda vendaCollectionNewVendaToAttach : vendaCollectionNew) {
                vendaCollectionNewVendaToAttach = em.getReference(vendaCollectionNewVendaToAttach.getClass(), vendaCollectionNewVendaToAttach.getVendaId());
                attachedVendaCollectionNew.add(vendaCollectionNewVendaToAttach);
            }
            vendaCollectionNew = attachedVendaCollectionNew;
            entradaSaida.setVendaCollection(vendaCollectionNew);
            List<FolhaPagamento> attachedFolhaPagamentoCollectionNew = new ArrayList<FolhaPagamento>();
            for (FolhaPagamento folhaPagamentoCollectionNewFolhaPagamentoToAttach : folhaPagamentoCollectionNew) {
                folhaPagamentoCollectionNewFolhaPagamentoToAttach = em.getReference(folhaPagamentoCollectionNewFolhaPagamentoToAttach.getClass(), folhaPagamentoCollectionNewFolhaPagamentoToAttach.getFolhaPagamentoId());
                attachedFolhaPagamentoCollectionNew.add(folhaPagamentoCollectionNewFolhaPagamentoToAttach);
            }
            folhaPagamentoCollectionNew = attachedFolhaPagamentoCollectionNew;
            entradaSaida.setFolhaPagamentoCollection(folhaPagamentoCollectionNew);
            List<Manutencao> attachedManutencaoCollectionNew = new ArrayList<Manutencao>();
            for (Manutencao manutencaoCollectionNewManutencaoToAttach : manutencaoCollectionNew) {
                manutencaoCollectionNewManutencaoToAttach = em.getReference(manutencaoCollectionNewManutencaoToAttach.getClass(), manutencaoCollectionNewManutencaoToAttach.getManutencaoId());
                attachedManutencaoCollectionNew.add(manutencaoCollectionNewManutencaoToAttach);
            }
            manutencaoCollectionNew = attachedManutencaoCollectionNew;
            entradaSaida.setManutencaoCollection(manutencaoCollectionNew);
            List<Compra> attachedCompraCollectionNew = new ArrayList<Compra>();
            for (Compra compraCollectionNewCompraToAttach : compraCollectionNew) {
                compraCollectionNewCompraToAttach = em.getReference(compraCollectionNewCompraToAttach.getClass(), compraCollectionNewCompraToAttach.getCompraId());
                attachedCompraCollectionNew.add(compraCollectionNewCompraToAttach);
            }
            compraCollectionNew = attachedCompraCollectionNew;
            entradaSaida.setCompraCollection(compraCollectionNew);
            entradaSaida = em.merge(entradaSaida);
            for (Venda vendaCollectionOldVenda : vendaCollectionOld) {
                if (!vendaCollectionNew.contains(vendaCollectionOldVenda)) {
                    vendaCollectionOldVenda.getEntradaSaidaCollection().remove(entradaSaida);
                    vendaCollectionOldVenda = em.merge(vendaCollectionOldVenda);
                }
            }
            for (Venda vendaCollectionNewVenda : vendaCollectionNew) {
                if (!vendaCollectionOld.contains(vendaCollectionNewVenda)) {
                    vendaCollectionNewVenda.getEntradaSaidaCollection().add(entradaSaida);
                    vendaCollectionNewVenda = em.merge(vendaCollectionNewVenda);
                }
            }
            for (FolhaPagamento folhaPagamentoCollectionOldFolhaPagamento : folhaPagamentoCollectionOld) {
                if (!folhaPagamentoCollectionNew.contains(folhaPagamentoCollectionOldFolhaPagamento)) {
                    folhaPagamentoCollectionOldFolhaPagamento.getEntradaSaidaCollection().remove(entradaSaida);
                    folhaPagamentoCollectionOldFolhaPagamento = em.merge(folhaPagamentoCollectionOldFolhaPagamento);
                }
            }
            for (FolhaPagamento folhaPagamentoCollectionNewFolhaPagamento : folhaPagamentoCollectionNew) {
                if (!folhaPagamentoCollectionOld.contains(folhaPagamentoCollectionNewFolhaPagamento)) {
                    folhaPagamentoCollectionNewFolhaPagamento.getEntradaSaidaCollection().add(entradaSaida);
                    folhaPagamentoCollectionNewFolhaPagamento = em.merge(folhaPagamentoCollectionNewFolhaPagamento);
                }
            }
            for (Manutencao manutencaoCollectionOldManutencao : manutencaoCollectionOld) {
                if (!manutencaoCollectionNew.contains(manutencaoCollectionOldManutencao)) {
                    manutencaoCollectionOldManutencao.getEntradaSaidaCollection().remove(entradaSaida);
                    manutencaoCollectionOldManutencao = em.merge(manutencaoCollectionOldManutencao);
                }
            }
            for (Manutencao manutencaoCollectionNewManutencao : manutencaoCollectionNew) {
                if (!manutencaoCollectionOld.contains(manutencaoCollectionNewManutencao)) {
                    manutencaoCollectionNewManutencao.getEntradaSaidaCollection().add(entradaSaida);
                    manutencaoCollectionNewManutencao = em.merge(manutencaoCollectionNewManutencao);
                }
            }
            for (Compra compraCollectionOldCompra : compraCollectionOld) {
                if (!compraCollectionNew.contains(compraCollectionOldCompra)) {
                    compraCollectionOldCompra.getEntradaSaidaCollection().remove(entradaSaida);
                    compraCollectionOldCompra = em.merge(compraCollectionOldCompra);
                }
            }
            for (Compra compraCollectionNewCompra : compraCollectionNew) {
                if (!compraCollectionOld.contains(compraCollectionNewCompra)) {
                    compraCollectionNewCompra.getEntradaSaidaCollection().add(entradaSaida);
                    compraCollectionNewCompra = em.merge(compraCollectionNewCompra);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = entradaSaida.getEntradaSaidaId();
                if (findEntradaSaida(id) == null) {
                    throw new NonexistentEntityException("The entradaSaida with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            EntradaSaida entradaSaida;
            try {
                entradaSaida = em.getReference(EntradaSaida.class, id);
                entradaSaida.getEntradaSaidaId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The entradaSaida with id " + id + " no longer exists.", enfe);
            }
            List<Venda> vendaCollection = entradaSaida.getVendaCollection();
            for (Venda vendaCollectionVenda : vendaCollection) {
                vendaCollectionVenda.getEntradaSaidaCollection().remove(entradaSaida);
                vendaCollectionVenda = em.merge(vendaCollectionVenda);
            }
            List<FolhaPagamento> folhaPagamentoCollection = entradaSaida.getFolhaPagamentoCollection();
            for (FolhaPagamento folhaPagamentoCollectionFolhaPagamento : folhaPagamentoCollection) {
                folhaPagamentoCollectionFolhaPagamento.getEntradaSaidaCollection().remove(entradaSaida);
                folhaPagamentoCollectionFolhaPagamento = em.merge(folhaPagamentoCollectionFolhaPagamento);
            }
            List<Manutencao> manutencaoCollection = entradaSaida.getManutencaoCollection();
            for (Manutencao manutencaoCollectionManutencao : manutencaoCollection) {
                manutencaoCollectionManutencao.getEntradaSaidaCollection().remove(entradaSaida);
                manutencaoCollectionManutencao = em.merge(manutencaoCollectionManutencao);
            }
            List<Compra> compraCollection = entradaSaida.getCompraCollection();
            for (Compra compraCollectionCompra : compraCollection) {
                compraCollectionCompra.getEntradaSaidaCollection().remove(entradaSaida);
                compraCollectionCompra = em.merge(compraCollectionCompra);
            }
            em.remove(entradaSaida);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<EntradaSaida> findEntradaSaidaEntities() {
        return findEntradaSaidaEntities(true, -1, -1);
    }

    public List<EntradaSaida> findEntradaSaidaEntities(int maxResults, int firstResult) {
        return findEntradaSaidaEntities(false, maxResults, firstResult);
    }

    private List<EntradaSaida> findEntradaSaidaEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from EntradaSaida as o order by o.dataVencimento");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public List<EntradaSaida> findEntradaSaidaEntities(Date dateInicio, Date dateFim) {

        List<EntradaSaida> entradaSaidasNew = new ArrayList<EntradaSaida>();
        List<EntradaSaida> entradaSaidas = findEntradaSaidaEntities();
        for (int i = 0; i < entradaSaidas.size(); i++) {
            EntradaSaida entradaSaida = entradaSaidas.get(i);
            if(entradaSaida.getDataVencimento().after(dateInicio) && entradaSaida.getDataVencimento().before(dateFim)){
                entradaSaidasNew.add(entradaSaida);
            }
        }
        return entradaSaidasNew;
    }

    public EntradaSaida findEntradaSaida(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(EntradaSaida.class, id);
        } finally {
            em.close();
        }
    }

    public int getEntradaSaidaCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from EntradaSaida as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
}
